<template>
    <div class="meter-report-container">
        <!-- 日期选择和导出区域 -->
        <div class="meter-report-header">
            <CustomDatePicker width="10rem" :isRange="false" v-model="date" />
            <div style="margin-left:auto ;">
                <span style="font-size: var(--font-size-small);margin-right: var(--gap-small);">表格布局</span>
                <el-segmented class="custom-style" v-model="tableSize" :options="sizeOptions" />
            </div>
            <!-- 新增刷新按钮 -->
            <el-button type="primary" :loading="isLoading" @click="handleRefresh">
                <template #icon>
                    <i class="fa fa-refresh"></i>
                </template>
                刷新
            </el-button>
            <el-button type="success" :loading="isExporting" @click="handleExport">
                <template #icon>
                    <i class="fa fa-download"></i>
                </template>
                导出
            </el-button>
        </div>

        <!-- 表格区域 -->
        <vxe-table :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" ref="tableRef"
            :size="tableSize" :style="{ fontSize: getFontSize() }" height="92%" v-loading="isLoading || isExporting"
            border align="center" :data="meterTableData" :tree-config="treeConfig" :export-config="exportConfig"
            :element-loading-text="isExporting ? '正在导出所有数据请稍等...' : '加载中...'">
            <!-- 固定列 -->
            <vxe-column tree-node fixed="left" field="meter_code" title="编号" />
            <vxe-column fixed="left" field="id" title="表号" />
            <vxe-column field="specification" title="规格" />
            <vxe-column field="yesterday_reading" title="上次读数"></vxe-column>
            <vxe-column field="current_reading" title="本次读数"></vxe-column>
            <vxe-column field="current_reading_time" title="时间">
                <template #default="{ row }">
                    {{ dayjs(row.current_reading_time).format('YYYY/MM/DD') }}
                </template>
            </vxe-column>
            <vxe-column fixed="right" field="Value" title="用量">
                <template #default="{ row }">
                    {{ formatFlowValue(row.Value) }}
                </template>
            </vxe-column>
        </vxe-table>
    </div>
    <SubMeterDialog v-model:visible="dialogVisible" :meter-data="selectedMeterData" :date="date" :table-size="tableSize"
        :fetch-data="fetchAndProcessMeterData" :load-child-nodes="loadChildNodes" />
</template>
<script setup>
import { ref, onMounted, watch, computed, reactive, nextTick } from "vue";
import dayjs from "dayjs";
import CustomDatePicker from "@/components/header/CustomDatePicker.vue";
import { formatFlowValue } from "@/utils/meterUtils";
import { getMeterReportApi, getMeterInfoApi } from "@/api/meter";
import SubMeterDialog from "../components/ElectricMeterDetailDialog.vue"
import { handleError } from "@/utils/handleError";
import { useCompanyStore } from "@/stores/company";
import convertToTreeData from '@/utils/convertToTreeData';
import { getMetersByLevel } from '@/utils/getMetersByLevel';
import * as XLSX from 'xlsx';

let sizeOptions = [{ label: '紧凑', value: 'small' }, { label: '标准', value: 'medium' }, { label: '宽松', value: 'large' }];

let tableSize = ref('medium');
let cellWidth = ref("auto")
const dialogVisible = ref(false);
const selectedMeterData = ref(null);
const Exported = ref(false);

// 新增：表计列表相关状态
const treeDataForChart = ref([]);
const meterList = ref([]);
const meterLevels = ref([]);
const currentMeter = ref(null);
const currentSelectedType = ref(2); // 电表类型

// 定义层级顺序
const LEVEL_ORDER = {
    'Ⅰ': 1, 'Ⅱ': 2, 'Ⅲ': 3, 'Ⅳ': 4, 'Ⅴ': 5, 'Ⅵ': 6, 'Ⅶ': 7, 'Ⅷ': 8, 'Ⅸ': 9, 'Ⅹ': 10, 'Ⅺ': 11
};

// 排序函数
function sortMeterList(list) {
    return [...list].sort((a, b) => {
        const [levelA, seqA] = a.meter_code.split('-');
        const [levelB, seqB] = b.meter_code.split('-');

        // 获取层级顺序
        const levelOrderA = LEVEL_ORDER[levelA] || 0;
        const levelOrderB = LEVEL_ORDER[levelB] || 0;

        // 如果层级不同，按层级排序
        if (levelOrderA !== levelOrderB) {
            return levelOrderA - levelOrderB;
        }
        // 如果层级相同，按编号排序
        return parseInt(seqA) - parseInt(seqB);
    });
}

// 获取表计列表
async function fetchMeterList(params = {}) {
    params = {
        type: currentSelectedType.value,
        ...params
    };
    try {
        isLoading.value = true;
        const res = await getMeterInfoApi(params);
        if (res.code !== 200) {
            throw new Error(res.message || '获取表计列表失败');
        }
        // 对列表进行排序
        meterList.value = sortMeterList(res.data);
        treeDataForChart.value = await convertToTreeData(meterList.value);
        meterLevels.value = getMetersByLevel(treeDataForChart.value);
        return res;
    } catch (error) {
        handleError(error, '获取表计列表失败');
        return { code: 500, data: [] };
    } finally {
        isLoading.value = false;
    }
}

const getFontSize = () => {
    let fontSize = "14px"
    switch (tableSize.value) {
        case 'small':
            fontSize = "12px"
            cellWidth.value = "60"
            break;
        case 'large':
            fontSize = "18px"
            cellWidth.value = "140"
            break;
        default:
            fontSize = "14px"
            cellWidth.value = "100"
            break;
    }
    return fontSize;
}

// 状态管理
const companyStore = useCompanyStore();

// 组件引用
const tableRef = ref(null);

// 响应式数据
const date = ref(dayjs().subtract(1, "day"));

const dateRange = computed(() => {
    const start = dayjs(date.value).startOf("day").valueOf();
    const end = dayjs(date.value).add(1, "day").startOf("day").valueOf();
    return [start, end];
});

const exportConfig = {
    type: 'xlsx',
    includeFooter: true,
    useStyle: true,
    isFooter: true,
    isColgroup: true,
    isAllExpand: true,
    filename: '电表日抄表记录',
    sheetName: '表计报表',
    modes: ['current']
}

const meterTableData = ref([]);
const isLoading = ref(false);
const isExporting = ref(false);

// 树形配置
const treeConfig = reactive({
    transform: true,
    rowField: "id",
    parentField: "parent_id",
    lazy: true,
    hasChild: "hasChild",
    showLine: true,
    loadMethod: ({ row }) => loadChildNodes(row),
    toggleMethod({ expanded, row }) {
        if (isExporting.value) return true
        if (row.level === 2) {
            dialogVisible.value = true;
            selectedMeterData.value = row;
        }
        return row.level === 1 ? true : false
    },
    iconOpen: 'vxe-icon-square-minus',
    iconClose: 'vxe-icon-square-plus'
});

async function fetchMeterDetail() {
    if (isLoading.value) return;

    try {
        meterTableData.value = [];
        isLoading.value = true;

        // 检查表计数据是否存在
        if (!treeDataForChart.value || !Array.isArray(treeDataForChart.value)) {
            console.warn('表计数据为空或格式不正确');
            return;
        }

        let results = await fetchAndProcessMeterData(treeDataForChart.value)
        meterTableData.value = results.filter(Boolean);

        // 等待表格渲染完成
        await nextTick();

        const table = tableRef.value;
        if (table) {
            await table.setAllTreeExpand(true);
        }
    } catch (error) {
        handleError(error, '获取电表数据失败')
    } finally {
        isLoading.value = false;
    }
}

// 新增刷新功能处理方法
async function handleRefresh() {
    try {
        // 重置Exported状态，确保下次导出时能重新展开节点
        Exported.value = false;

        // 显示刷新提示
        ElMessage({
            type: 'info',
            title: '提示',
            message: '正在刷新数据...',
            duration: 2000
        });

        // 重新获取表计数据
        await fetchMeterDetail();

        // 刷新成功提示
        ElMessage({
            type: 'success',
            title: '成功',
            message: '数据刷新成功',
            duration: 2000
        });
    } catch (error) {
        handleError(error, '获取电表数据失败')
    }
}

async function fetchAndProcessMeterData(meters) {
    try {
        let res = await Promise.all(meters.map(async item => {
            return new Promise((resolve) => {
                getMeterReportApi({
                    id: item.id,
                    start_time: dateRange.value[0],
                    end_time: dateRange.value[1]
                }).then((res) => {
                    if (!res || !res.aggregated_data || !res.aggregated_data[0]) {
                        console.warn(`表计${item.meter_code}没有数据`);
                        resolve(null);
                        return;
                    }
                    let data = res.aggregated_data[0];
                    let localMeterData = {
                        ...item, hasChild: Array.isArray(item.children) && item.children.length > 0,
                        customChildren: item.children,
                        current_reading: data.end || 0,
                        Value: data.Value || 0,
                        yesterday_reading: data.begin || 0,
                        current_reading_time: data.start_time || Date.now()
                    }
                    resolve(localMeterData)
                }).catch((error) => {
                    handleError(error, `获取表计${item.meter_code}数据失败`);
                    resolve(null);
                });
            })
        }))
        return res
    } catch (error) {
        handleError(error, '获取电表数据失败');
        return [];
    }
}

async function loadChildNodes(parentNode) {
    try {
        if (!parentNode || !parentNode.customChildren || !Array.isArray(parentNode.customChildren)) {
            console.warn('父节点数据无效:', parentNode);
            return [];
        }

        const children = await fetchAndProcessMeterData(parentNode.customChildren);
        const validChildren = children.filter(Boolean);
        return validChildren;
    } catch (error) {
        handleError(error, '获取子节点数据失败');
        return [];
    }
}

// 获取所有表计数据（展平树形结构）
async function getAllMeterDataFlat() {
    const allData = [];

    // 递归获取所有节点数据
    async function collectNodeData(nodes, level = 1) {
        for (const node of nodes) {
            if (!node) continue;

            // 添加当前节点
            allData.push({
                ...node,
                level: level
            });

            // 获取子节点数据
            if (node.hasChild && node.customChildren) {
                const childrenData = await loadChildNodes(node);
                if (childrenData && childrenData.length > 0) {
                    await collectNodeData(childrenData, level + 1);
                }
            }
        }
    }

    // 开始收集所有表计数据
    await collectNodeData(meterTableData.value);

    return allData;
}

// 格式化数据行
function formatDataRow(row, index) {
    return [
        index + 1, // 序号
        row.meter_code || '',
        row.id || '',
        row.specification || '',
        row.yesterday_reading !== undefined ? row.yesterday_reading : '无数据',
        row.current_reading !== undefined ? row.current_reading : '无数据',
        row.current_reading_time ? dayjs(row.current_reading_time).format('YYYY/MM/DD') : '',
        formatFlowValue(row.Value)
    ];
}

// 主导出函数
async function handleExport() {
    try {
        isExporting.value = true;

        ElMessage({
            type: 'info',
            message: '正在准备导出数据...',
        });

        // 1. 获取所有表计数据（展平）
        const allMeterData = await getAllMeterDataFlat();

        // 2. 创建工作簿和工作表
        const workbook = XLSX.utils.book_new();

        // 3. 创建表头
        const headers = [
            ['序号', '编号', '表号', '规格', '上次读数', '本次读数', '时间', '用量']
        ];

        // 4. 准备数据
        const sheetData = [...headers];

        // 添加表计数据
        allMeterData.forEach((row, index) => {
            const dataRow = formatDataRow(row, index);
            sheetData.push(dataRow);
        });

        // 5. 创建工作表
        const worksheet = XLSX.utils.aoa_to_sheet(sheetData);

        // 6. 设置列宽
        const columnWidths = [
            { wch: 8 },  // 序号
            { wch: 20 }, // 编号
            { wch: 15 }, // 表号
            { wch: 10 }, // 规格
            { wch: 15 }, // 上次读数
            { wch: 15 }, // 本次读数
            { wch: 15 }, // 时间
            { wch: 12 }, // 用量
        ];

        worksheet['!cols'] = columnWidths;

        // 7. 添加工作表到工作簿
        XLSX.utils.book_append_sheet(workbook, worksheet, '电表日抄表');

        // 8. 生成文件名
        const selectedDate = dayjs(date.value).format('YYYY年MM月DD日');
        const fileName = `电表日抄表记录_${selectedDate}.xlsx`;

        // 9. 导出文件
        XLSX.writeFile(workbook, fileName);

        ElMessage({
            type: 'success',
            message: '导出成功！',
        });

    } catch (error) {
        console.error('导出失败:', error);
        ElMessage({
            type: 'error',
            message: '导出失败，请重试',
        });
        handleError(error, '导出失败');
    } finally {
        isExporting.value = false;
    }
}

// 监听数据变化 - 使用本地状态而不是store
watch(
    [() => dateRange.value, () => treeDataForChart.value],
    () => {
        if (treeDataForChart.value && treeDataForChart.value.length > 0) {
            fetchMeterDetail();
        }
    },
    { deep: true }
);

// 监听公司改变
watch(
    () => companyStore.currentCompany,
    async (newCompany) => {
        if (newCompany) {
            try {
                // 重置Exported状态
                Exported.value = false;

                // 重新获取表计列表
                await fetchMeterList();

                // 重新获取数据
                await fetchMeterDetail();
            } catch (error) {
                handleError(error, '切换公司失败');
            }
        }
    }
);

// 生命周期钩子
onMounted(async () => {
    try {
        // 确保设置为电表类型
        currentSelectedType.value = 2;

        // 获取表计列表
        await fetchMeterList();

        // 获取表计数据
        await fetchMeterDetail();
    } catch (error) {
        handleError(error, '初始化失败');
    }
});
</script>
<style scoped>
.meter-report-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.meter-report-header {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
}

.meter-report-body {
    flex: 1;
}
</style>